<script lang="ts" setup>
import type { LicenseListItem } from '@/apis/model/License'
import hljs from 'highlight.js/lib/core'
import accesslog from 'highlight.js/lib/languages/accesslog'
import { getCertRecordLogApi } from '@/apis/modules/cert'
// import { getCertRecordLogApi } from '@/apis/modules/cert'

const emit = defineEmits<IEmit>()
hljs.registerLanguage('accesslog', accesslog)
const visible = defineModel<boolean>('visible', { required: true })
const record = defineModel<
  { id: string, site_domain: string } | LicenseListItem
>('record', {
  required: true,
})
// 刷新表格事件
interface IEmit {
  (event: 'refreshRow', row: LicenseListItem): void
}
const { el, loading, isEnd, request, classNames, txtContent } = useTerminal({
  api: getCertRecordLogApi,
  body: { id: record.value?.id },
  immediate: false,
})
/**
 * 轮询逻辑
 */
let timer: NodeJS.Timer
const clear = watch(
  () => isEnd.value,
  (val) => {
    if (val) {
      clearInterval(timer)
      clear()
    }
  },
)
watchEffect(() => {
  if (visible.value && !isEnd.value) {
    pollMessage()
  } else {
    clearInterval(timer)
    clear()
  }
})
async function pollMessage() {
  timer = await setInterval(() => {
    clear()
    request({ id: record.value.id })
  }, 3 * 1000)
  document.addEventListener('DOMContentLoaded', () => {
    const codeBlocks = document.querySelectorAll('.hljs')
    codeBlocks.forEach((block) => {
      block.scrollTop = block.scrollHeight
    })
  })
}
function handleOpen() {
  request({ id: record.value.id })
}
function handleCancel() {
  visible.value = false
  txtContent.value = ''
}
watch(
  () => isEnd.value,
  async (v) => {
    if (v && ![1, 2].includes(record.value?.apply_result)) {
      // const res = await getCertApi({ id: record.value.id! })
      // if (!res)
      //   return
      // emit('refreshRow', res)
    }
  },
  {
    immediate: true,
  },
)
watch(
  () => txtContent.value,
  (val) => {
    setTimeout(() => {
      if (val) {
        const pre = document.querySelector('pre')
        const element = document.querySelector('code')
        pre?.scrollTo({
          top: element?.offsetHeight,
          behavior: 'smooth',
        })
      }
    }, 100)
  },
)

function handleDownload() {
  useDownloadTxt(txtContent.value, record.value?.site_domain)
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    title="证书日志"
    :loading="loading"
    :mask-closable="false"
    :class="classNames"
    dialog-class="node-scroll hide-header"
    width="1000px"
    body-class="!pb-0"
    :before-close="handleCancel"
    :before-open="handleOpen"
  >
    <highlightjs
      ref="el"
      language="accesslog"
      :autodetect="false"
      :code="txtContent"
    />

    <template #footer>
      <div>
        <a-button
          class="ml-6 w-[74px]"
          @click="handleCancel"
        >
          关闭
        </a-button>

        <a-button
          class="footer-btn ml-3"
          :disabled="!isEnd"
          @click="handleDownload"
        >
          下载日志
        </a-button>
      </div>
    </template>
  </resource-dialog>
</template>

<style lang="less">
.node-scroll {
  .arco-modal-body {
    overflow: hidden !important;
  }
}

.log-wrap {
  background-color: var(--color-text-1);
  @apply h-85 ! p-4 text-white rounded;
}

pre {
  height: 520px;
  //max-height: 520px;
  overflow: auto !important;
  margin: 0;
  overflow-y: auto;
}

pre code.hljs {
  display: block;
  overflow: auto;
  padding: 5px 10px;
  color: #c9d1d9;
  background: #0d1117;
  //height: inherit !important;
  line-height: initial !important;
  // overflow-y: auto;
  //display: flex;
  min-height: 520px;
  flex-direction: column-reverse;
}

.footer-btn {
  background-color: rgb(255 255 255 / var(--un-bg-opacity)) !important;
  color: var(--color-text-1) !important;
  border: 1px solid var(--border-2, #e5e6eb) !important;
  &:hover {
    background-color: #f2f3f5 !important;
  }
}
</style>
